<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单编号" prop="orderId">
        <el-input
          v-model="queryParams.orderId"
          placeholder="请输入订单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="体检日期">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          @change="handleDateChange"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格 -->
    <el-table v-loading="loading" :data="reportList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="体检套餐名" align="center" prop="packageName" />
      <el-table-column label="体检机构" align="center" prop="hospitalName" />
      <el-table-column label="体检人" align="center" prop="patientName" />
      <el-table-column label="身份证" align="center" prop="idCard" />
      <el-table-column label="体检日期" align="center" prop="reportDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.reportDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleViewReport(scope.row)"
          >查看报告</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:report:remove']"
          >删除报告</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { listReport, delReport } from "@/api/physicalExamination/report";
import { listPatient } from "@/api/hospital/patient";
import { listHospital } from "@/api/hospital/hospital";
import { listPackage } from "@/api/physicalExamination/package";

export default {
  name: "Report",
  data() {
    return {
      loading: true,
      ids: [],
      multiple: true,
      showSearch: true,
      total: 0,
      reportList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderId: null,
        reportDateStart: null,
        reportDateEnd: null
      },
      dateRange: []
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询体检报告列表 */
    async getList() {
      this.loading = true;
      try {
        const response = await listReport(this.queryParams);
        const reports = response.rows;
        this.total = response.total;

        // 获取附加信息
        await this.enrichReportData(reports);
        this.reportList = reports;
        this.loading = false;
      } catch (error) {
        this.loading = false;
        this.$modal.msgError("数据加载失败: " + error.message);
      }
    },
    /** 丰富报告数据 */
    async enrichReportData(reports) {
      if (!reports || reports.length === 0) return;

      // 获取所有患者信息
      const patientIds = [...new Set(reports.map(r => r.patientId))].join(',');
      const patientRes = await listPatient({ patientIds });
      const patientMap = new Map(patientRes.rows.map(p => [p.id, p]));

      // 获取所有医院信息
      const hospitalIds = [...new Set(reports.map(r => r.hospitalId))].join(',');
      const hospitalRes = await listHospital({ hospitalIds });
      const hospitalMap = new Map(hospitalRes.rows.map(h => [h.id, h.name]));

      // 获取所有套餐信息
      const packageIds = [...new Set(reports.map(r => r.packageId))].join(',');
      const packageRes = await listPackage({ packageIds });
      const packageMap = new Map(packageRes.rows.map(p => [p.id, p.packageName]));

      // 合并数据
      reports.forEach(report => {
        const patient = patientMap.get(report.patientId);
        const hospital = hospitalMap.get(report.hospitalId);
        const pkg = packageMap.get(report.packageId);

        report.patientName = patient?.name || '未知';
        report.idCard = patient?.idCard || '未知';
        report.hospitalName = hospital || `未知医院${report.hospitalId}`;
        report.packageName = pkg || `未知套餐${report.packageId}`;
      });
    },
    /** 处理日期范围变化 */
    handleDateChange(val) {
      if (val) {
        this.queryParams.reportDateStart = val[0];
        this.queryParams.reportDateEnd = val[1];
      } else {
        this.queryParams.reportDateStart = null;
        this.queryParams.reportDateEnd = null;
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        orderId: null,
        reportDateStart: null,
        reportDateEnd: null
      };
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.reportId);
      this.multiple = !selection.length;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const reportIds = row.reportId || this.ids;
      this.$modal.confirm('是否确认删除体检报告编号为"' + reportIds + '"的数据项？').then(() => {
        return delReport(reportIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 查看报告操作 */
    handleViewReport(row) {
      this.$router.push({
        path: '/physicalExamination/report/details', // 修改为报告详情页路由
        query: { id: row.reportId } // 使用 reportId 作为查询参数
      });
    }
  }
};
</script>
<style scoped>
/* 保持原有样式 */
</style>
